package com.media.publish

import android.annotation.SuppressLint
import android.app.AlertDialog
import android.content.Intent
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.os.CountDownTimer
import android.os.Handler
import android.text.Editable
import android.text.TextUtils
import android.text.TextWatcher
import android.view.View
import android.widget.TextView
import androidx.annotation.RequiresApi
import androidx.recyclerview.widget.ItemTouchHelper
import com.baidu.mapapi.search.core.PoiInfo
import com.baselibrary.BaseConstant
import com.baselibrary.Constants
import com.baselibrary.MessageBus
import com.baselibrary.WikiConstants
import com.baselibrary.activity.BaseActivity
import com.baselibrary.bean.PublishEventBusBean
import com.baselibrary.bean.ReleaseTopicBean
import com.baselibrary.extension.checkNotNull
import com.baselibrary.extension.toast
import com.baselibrary.manager.AppManager
import com.baselibrary.manager.DialogManager
import com.baselibrary.manager.RecycleViewManager
import com.baselibrary.utils.*
import com.baselibrary.utils.EventBusUtils
import com.baselibrary.view.MyCircleProgress
import com.media.publish.adapter.ImageVideoAdapter
import com.liaoinstan.springview.utils.DensityUtil
import com.media.R
import com.media.databinding.ActivityReleaseImageVideoBinding
import com.media.image.ImageModel
import com.media.revision.RevisionMediaActivity
import com.xinlan.imageeditlibrary.editimage.utils.SpacesTopDec
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import com.media.publish.adapter.RecoTopicAdapter
import com.media.publish.bean.PublishBean
import com.media.publish.service.UploadMediaService
import com.media.publish.utils.RecyUtils
import java.io.Serializable

/**
 * @Author: Carl
 * @Description: java类作用描述
 * @CreateDate: 2020-09-21 21:33j
 * @UpdateUser: Carl
 * @UpdateDate: 2020-09-21 21:33
 * @UpdateRemark: 填写更新说明
 */
class ReleaseDynamicActivity : BaseActivity(), View.OnClickListener, ImageVideoAdapter.OnItemClickListener, TextWatcher {

    private lateinit var mBinding: ActivityReleaseImageVideoBinding
    private lateinit var mViewModel: ReleaseDynamicViewModel
    private lateinit var mImageVideoAdapter: ImageVideoAdapter
    private lateinit var mRecoTopicAdapter: RecoTopicAdapter
    private var DYNAMICTYPE = 0 //1图文；2视频
    private var mAddress = ""
    private var mProvinceId = "0"
    private var mCityId = "0"
    private val mDistrictId = "0"
    private var wineryId = ""
    private var wineryCode = ""
    private var mVideoUrl = ""
    private var mVideoCover = ""
    private var mDraftTopicBean: ReleaseTopicBean.DataBean? = null
    private var mQiNiuSDCardVideoPath: String? = null
    private lateinit var mTouchHelper: ItemTouchHelper
    private var isAddTopic = false
    private val tHandler = Handler()
    private var mPublishType: String = ""
    private lateinit var mIntent: Intent
    private var mp4Path = ""
    private val mVideoEditScheme = "scheme://main/mainVideoEditActivity"
    override fun getLayoutId(): Int {
        return R.layout.activity_release_image_video
    }

    override fun init() {

        mBinding = getDataBinding<ActivityReleaseImageVideoBinding>()
        mViewModel = getActivityViewModelProvider(this).get(ReleaseDynamicViewModel::class.java)
        mViewModel.mBinding = mBinding
        initData()

        mViewModel.reqDefSearchTopics()

        loadData()
        initListener()
        initObserve()
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this)
        }

    }

    private fun initListener() {
        mBinding.tvImageVideoTopic.setOnClickListener(this)
        mBinding.llExisphone.setOnClickListener(this)
        mBinding.ivImagevideoBack.setOnClickListener(this)
        mBinding.tvRelease.setOnClickListener(this)
        mBinding.ivImagevideoTieshi.setOnClickListener(this)
        mBinding.tvImageVideoLocation.setOnClickListener(this)
        mBinding.etImagevideoInput.addTextChangedListener(this)
        mImageVideoAdapter.setOnClickListener(this)
        mRecoTopicAdapter.setOnItemClickListener {
            isAddTopic = true
            mDraftTopicBean = it
            mViewModel.getMoreGiveGuide(mBinding, mViewModel.mMediaPathList, isAddTopic, DYNAMICTYPE)
            mBinding.tvImageVideoTopic.text = ColorTextUtils.substringDes(it.name, 6)
        }
    }

    private fun initData() {
        DYNAMICTYPE = intent.getIntExtra("Dynamictype", 0)
        mRecoTopicAdapter = RecoTopicAdapter(this)
        mImageVideoAdapter = ImageVideoAdapter(this, mViewModel.mMediaPathList)
        mImageVideoAdapter.setDynamictype(DYNAMICTYPE)

        mBinding.rvImageVideoRecTopic.adapter = mRecoTopicAdapter
        mBinding.rvImagevideo.addItemDecoration(SpacesRightDec(DensityUtil.dip2px(applicationContext, 8f)))
        mBinding.rvImagevideo.addItemDecoration(SpacesTopDec(DensityUtil.dip2px(applicationContext, 10f)))
        mBinding.rvImagevideo.adapter = mImageVideoAdapter
        mTouchHelper = RecyUtils.itemTouchHelper(mImageVideoAdapter, mViewModel.mMediaPathList, Constants.PUBLISH_IMG_MAX, mBinding.ivImageVideoDrag)
        mViewModel.setItemHelper(mTouchHelper, mImageVideoAdapter)
        mIntent = Intent(this, UploadMediaService::class.java)

    }

    @SuppressLint("NotifyDataSetChanged") private fun loadData() {
        if (DYNAMICTYPE == 1) {
            val mIntentPicturePath = intent.getStringArrayListExtra("result")!!
            if (mIntentPicturePath.checkNotNull()) {
                mViewModel.mMediaPathList.addAll(mIntentPicturePath)
                mViewModel.mSDPathList.addAll(mIntentPicturePath)
                mImageVideoAdapter.setData(mViewModel.mMediaPathList)
                mImageVideoAdapter.setDynamictype(DYNAMICTYPE)
                mImageVideoAdapter.notifyDataSetChanged()
                mViewModel.setItemHelper(mTouchHelper, mImageVideoAdapter)
            }
            mViewModel.getMoreGiveGuide(mBinding, mViewModel.mMediaPathList, isAddTopic, DYNAMICTYPE)
        } else {
            try {
                mp4Path = intent.getStringExtra(VideoEditActivity.MP4_PATH)!!
                mViewModel.mMediaPathList.add(mp4Path)
                mViewModel.setItemHelper(mTouchHelper, mImageVideoAdapter)
                mImageVideoAdapter.setData(mViewModel.mMediaPathList)
                mImageVideoAdapter.setDynamictype(DYNAMICTYPE)
                mImageVideoAdapter.notifyDataSetChanged()
            } catch (e: Exception) {
            }
        }
    }

    private fun initObserve() {
        mViewModel.topicListLD.observe(this, androidx.lifecycle.Observer {
            if (it.checkNotNull()) {
                mRecoTopicAdapter.setData(it)
                mBinding.rvImageVideoRecTopic.postDelayed({
                    mDraftTopicBean?.let { topicBean ->
                        if (topicBean.id != 0) {
                            val jumpPos = mRecoTopicAdapter.setSelectData(topicBean)
                            if (jumpPos != -1) RecycleViewManager.smoothMoveToPosition1(mBinding.rvImageVideoRecTopic, jumpPos)
                        }
                    }
                }, 500)
            }
        })

    }

    @SuppressLint("NewApi", "NonConstantResourceId") override fun onClick(view: View) {
        when (view.id) {
            R.id.iv_imagevideo_back -> {
                finish()
            }
            R.id.tv_imageVideo_topic -> {
                val topicIntent = Intent(this, SearchTopicActivity::class.java)
                startActivityForResult(topicIntent, ReleaseDynamicViewModel.REQUEST_SREARCH_TOPIC)
            }
            R.id.tv_imageVideo_location -> {
                startActivityForResult(Intent(this, BaiduMapLocationActivity::class.java),
                    ReleaseDynamicViewModel.REQUEST_LOCATION
                )
            }
            R.id.ll_exisphone -> {
                mBinding.ivExisphone.isSelected = !mBinding.ivExisphone.isSelected
            }
            R.id.iv_imagevideo_tieshi -> {
                if (DoubleClickHelper.isOnDoubleClick()) return
                DialogManager.showTipsDialog(this)
            }
            R.id.tv_release -> {
                if (DoubleUtils.isFastDoubleClick()) return
                mIntent.action = UploadMediaService.ACTION_PUBLISH
                val publishBean = PublishBean()
                publishBean.saveMedia = mBinding.ivExisphone.isSelected
                publishBean.dynamicType = DYNAMICTYPE
                publishBean.provinceId = mDistrictId
                publishBean.cityId = mCityId
                publishBean.videoSourcePath = mp4Path
                publishBean.content = mBinding.etImagevideoInput.text.toString()
                publishBean.tagstr = if (mDraftTopicBean == null) "[]" else "[" + mDraftTopicBean?.id + "]"
                publishBean.wineryId = wineryId
                publishBean.address = mAddress
                publishBean.publishType = mPublishType
                publishBean.videoCover = mVideoCover
                publishBean.relatedTopic = mDraftTopicBean?.name ?: ""
                publishBean.images = mViewModel.mMediaPathList
                publishBean.x = (ScreenUtils.getScreenX(this) / 2).toFloat()
                publishBean.y = (ScreenUtils.getScreenY(this) / 2).toFloat()
                publishBean.imageUrls = ArrayList()
                publishBean.wineryCode = SpUtils.getInstance().currentWineryInfo.wineryCode//如果是经营者，在社区发布动态也要同步到酒窖
                mIntent.putExtra("data", publishBean as Serializable)
                startService(mIntent)
                if (TextUtils.isEmpty(wineryCode)) {//社区动态发布
                    val activityIntent = this.packageManager.getLaunchIntentForPackage("com.hanxiang.hankol")
                    activityIntent?.flags = Intent.FLAG_ACTIVITY_CLEAR_TOP
                    EventBusUtils.sendNotify(MessageBus.msgid_notify_change_to_follow)
                    if (mViewModel.mMediaPathList.size > 0) {
                        EventBusUtils.sendNotify1Value(MessageBus.msgid_notify_start_publish, mViewModel.mMediaPathList[0])
                    }
                    startActivity(activityIntent)
                    finish()
                } else {
                    //酒窖动态发布
                    showLoading()
                }
            }
        }
    }

    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (data == null) return
        when (requestCode) {
            ReleaseDynamicViewModel.REQUEST_LOCATION -> {
                if (data.hasExtra("location")) {
                    val poiItem: PoiInfo = data.getParcelableExtra("location")!!
                    mAddress = poiItem.name
                    mProvinceId = SpUtils.getString(this, "province_id")
                    mCityId = SpUtils.getString(this, "city_id")
                    mBinding.tvImageVideoLocation.text = ColorTextUtils.substringDes(poiItem.name, 6)
                } else {
                    mAddress = ""
                    mProvinceId = "0"
                    mCityId = "0"
                    mBinding.tvImageVideoLocation.text = "所在位置"
                }
            }
            ReleaseDynamicViewModel.REQUEST_SREARCH_TOPIC -> {
                if (data.hasExtra("topicBean")) {
                    val topicBean: ReleaseTopicBean.DataBean = data.getParcelableExtra("topicBean")!!
                    mDraftTopicBean = topicBean
                    mBinding.tvImageVideoTopic.text = ColorTextUtils.substringDes(topicBean.name, 6)
                    isAddTopic = true
                    val jumpPos = mRecoTopicAdapter.setSelectData(topicBean)
                    if (jumpPos != -1) RecycleViewManager.smoothMoveToPosition1(mBinding.rvImageVideoRecTopic, jumpPos)

                } else {
                    mBinding.tvImageVideoTopic.text = "添加话题"
                    isAddTopic = false
                    mRecoTopicAdapter.upSelect(-1)
                }
                mViewModel.getMoreGiveGuide(mBinding, mViewModel.mMediaPathList, isAddTopic, DYNAMICTYPE)
            }
            ReleaseDynamicViewModel.REQUEST_IMAGEEDIT -> if (resultCode == ReleaseDynamicViewModel.RESULT_EDITIMGOVVER) {
                val mPicturePath = data.getStringArrayListExtra("result")
                if (mPicturePath != null && mPicturePath.size > 0) {
                    mViewModel.mMediaPathList.addAll(mPicturePath)
                    mViewModel.setItemHelper(mTouchHelper, mImageVideoAdapter)
                    mViewModel.mSDPathList.addAll(mPicturePath)
                    mImageVideoAdapter.setData(mViewModel.mMediaPathList)
                    mImageVideoAdapter.setDynamictype(DYNAMICTYPE)
                    mImageVideoAdapter.notifyDataSetChanged()
                    mViewModel.getMoreGiveGuide(mBinding, mViewModel.mMediaPathList, isAddTopic, DYNAMICTYPE)
                }
            }
            ReleaseDynamicViewModel.REQUEST_QINIU -> if (resultCode == ReleaseDynamicViewModel.RESULT_QINIU) {
            }
            ReleaseDynamicViewModel.REQUEST_COVERS -> if (resultCode == ReleaseDynamicViewModel.RESULT_COVERS) {
                mVideoCover = data.getStringExtra("coversSelectUrl")!!
                mViewModel.mMediaPathList.clear()
                mViewModel.mMediaPathList.add(mVideoCover)
                mViewModel.setItemHelper(mTouchHelper, mImageVideoAdapter)
                mImageVideoAdapter.setData(mViewModel.mMediaPathList)
                mImageVideoAdapter.setDynamictype(DYNAMICTYPE)
                mImageVideoAdapter.notifyDataSetChanged()
            }
        }
    }
    override fun onItemClick(pos: Int, list: ArrayList<String>) {
        if (DYNAMICTYPE == 1) {
            val mPreViewIntent = Intent(this, PreviewMediaActivity::class.java)
            mPreViewIntent.putStringArrayListExtra(WikiConstants.WIKI_PICTURE_LIST, list)
            mPreViewIntent.putExtra(WikiConstants.WIKI_PICTURE_INDEX, pos)
            startActivity(mPreViewIntent)
            ToastUtils.showShort(this,list.size.toString())
        }
        if (DYNAMICTYPE == 2) {
            val videoBundle = Bundle()
            if (!TextUtils.isEmpty(mQiNiuSDCardVideoPath)) {
                videoBundle.putString("preVideoPath", mQiNiuSDCardVideoPath)
            } else {
                videoBundle.putString("preVideoPath", mp4Path)
            }
            videoBundle.putString("preVideoCover", mVideoCover)
            openActivity(PreViewVideoActivity::class.java, videoBundle)
        }
    }
    //首页大改版：跳转图片编辑
  /*  override fun onItemClick(pos: Int, list: ArrayList<String>) {
        if (DYNAMICTYPE == 1) {//首页大改版：跳转图片编辑
            var intent = Intent()
            intent.setClass(this, EditImgMainActivity::class.java);
            intent.putStringArrayListExtra(EditImgMainActivity.FILE_PATH_LIST, *//*AlbumManageUtils.startEditorAct(getApplicationContext(), list)*//*list);
            *//*intent.putExtra("isForResult", isForResult);
            intent.putExtra("isPassEventbus", isPassEventbus);*//*
            startActivityForResult(intent, 101);
*//*            val mPreViewIntent = Intent(this, PreviewMediaActivity::class.java)
            mPreViewIntent.putStringArrayListExtra(WikiConstants.WIKI_PICTURE_LIST, list)
            mPreViewIntent.putExtra(WikiConstants.WIKI_PICTURE_INDEX, pos)
            startActivity(mPreViewIntent)*//*
        }
        if (DYNAMICTYPE == 2) {//首页大改版：跳转视频编辑
            val intentVideo = Intent(Intent.ACTION_VIEW, Uri.parse(mVideoEditScheme))
            intentVideo.putExtra("isEdit", true)
            *//*intentVideo.putExtra("isPassEventbus", isPassEventbus)*//*
            intentVideo.putExtra("videoPath", if (!TextUtils.isEmpty(mQiNiuSDCardVideoPath)) mQiNiuSDCardVideoPath else mp4Path) //剪辑界面需要
            intentVideo.putExtra("MP4_PATH", if (!TextUtils.isEmpty(mQiNiuSDCardVideoPath)) mQiNiuSDCardVideoPath else mp4Path) //编辑界面需要
            startActivity(intentVideo)
*//*            val videoBundle = Bundle()
            if (!TextUtils.isEmpty(mQiNiuSDCardVideoPath)) {
                videoBundle.putString("preVideoPath", mQiNiuSDCardVideoPath)
            } else {
                videoBundle.putString("preVideoPath", mp4Path)
            }
            videoBundle.putString("preVideoCover", mVideoCover)
            openActivity(PreViewVideoActivity::class.java, videoBundle)*//*
        }
    }*/

    override fun onVideoCoversClick() {
        if (DYNAMICTYPE == 2) {
            val mCoverIntent = Intent(this, CoverSelectActivity::class.java)
            if (!TextUtils.isEmpty(mQiNiuSDCardVideoPath)) {
                mCoverIntent.putExtra("videoPath", mQiNiuSDCardVideoPath)
            } else {
                mCoverIntent.putExtra("videoPath", mp4Path)
            }
            startActivityForResult(mCoverIntent, ReleaseDynamicViewModel.REQUEST_COVERS)
        }
    }

    override fun onAddItemClick() {
        if (DoubleClickHelper.isOnDoubleClick()) return
        DialogManager.showDynamicDialog(this, object : OnClickListener {
            override fun onClick(view: View, `object`: Any) {
                if (`object` as Int == 1) {
                    val intent = Intent(Intent.ACTION_VIEW, Uri.parse("scheme://release/releaseVideoRecord"))
                    intent.putExtra("typeVideo", "1")
                    intent.putExtra("isVisibility", true)
                    intent.putExtra("jumpType", 1)
                    intent.putExtra("isForResult", true)
                    startActivityForResult(intent, ReleaseDynamicViewModel.REQUEST_IMAGEEDIT)
                    //打开七牛云拍照
                    DYNAMICTYPE = 1
                    return
                }
                if (`object` == 2) {
                    //打开相册
                    val intent = Intent(this@ReleaseDynamicActivity, RevisionMediaActivity::class.java)
                    intent.putExtra("type", ImageModel.TYPE_IMAGE)
                    intent.putExtra("maxstr", Constants.PUBLISH_IMG_MAX - mViewModel.mMediaPathList.size)
                    intent.putExtra("jumpType", 1)
                    intent.putExtra("isForResult", true)
                    intent.putExtra("isForResult", true)
                    startActivityForResult(intent, ReleaseDynamicViewModel.REQUEST_IMAGEEDIT)
                    DYNAMICTYPE = 1
                }
            }

            override fun onLongClick(view: View, o: Any?) {}
        })
    }

    override fun onDeleteItemClick(pos: Int, list: ArrayList<String>) {
        PopUtils.showOkCancelDialog(this, "确认删除", object : PopUtils.ICallBack {
            override fun clickOk() {
                mViewModel.mMediaPathList.removeAt(pos)
                if (mViewModel.mMediaPathList.size == 1) {
                    mViewModel.setItemHelper(mTouchHelper, mImageVideoAdapter)
                }
                mImageVideoAdapter.setData(mViewModel.mMediaPathList)
                mImageVideoAdapter.setDynamictype(DYNAMICTYPE)
                mImageVideoAdapter.notifyDataSetChanged()
                mViewModel.getMoreGiveGuide(mBinding, mViewModel.mMediaPathList, isAddTopic, DYNAMICTYPE)
            }

            override fun clickCancel() {

            }

        }, false, "确认", "取消")
    }

    override fun beforeTextChanged(charSequence: CharSequence, i: Int, i1: Int, i2: Int) {}
    override fun onTextChanged(charSequence: CharSequence, i: Int, i1: Int, i2: Int) {}

    @SuppressLint("SetTextI18n") override fun afterTextChanged(editable: Editable) {
        mBinding.tvImagevideoNumber.text = "${editable.toString().length}/800"
        mViewModel.getMoreGiveGuide(mBinding, mViewModel.mMediaPathList, isAddTopic, DYNAMICTYPE)
    }

    @Subscribe(threadMode = ThreadMode.MAIN, sticky = true) fun onEvent(messageBus: MessageBus) {
        if (messageBus.codeType == MessageBus.msgid_publish_dynamic_type) {
            val mPublishEventBusBean = messageBus.message as PublishEventBusBean
            mPublishType = mPublishEventBusBean.publishType
            when (mPublishEventBusBean.publishType) {
                BaseConstant.PUBLISH_PLUS -> {
                }
                BaseConstant.PUBLISH_TOPIC -> {
                    mBinding.tvImageVideoTopic.text = ColorTextUtils.substringDes(mPublishEventBusBean.typeName, 6)
                    mDraftTopicBean = ReleaseTopicBean.DataBean()
                    mDraftTopicBean?.name = mPublishEventBusBean.typeName
                    mDraftTopicBean?.id = mPublishEventBusBean.typeId.toInt()
                    isAddTopic = true
                    mViewModel.getMoreGiveGuide(mBinding, mViewModel.mMediaPathList, isAddTopic, DYNAMICTYPE)
                }
                BaseConstant.PUBLISH_FOLLOW -> {

                }
                BaseConstant.PUBLISH_WINE_CELLAR -> {
                    wineryId = mPublishEventBusBean.typeId.toString()

                }
                BaseConstant.PUBLISH_WINE_CELLAR_NEW -> {
                    wineryCode = mPublishEventBusBean.typeIdStr
                }
            }
        } else if (messageBus.codeType == MessageBus.msgid_notify_publish_success) {
            //当发布酒窖动态成功后 dismiss loading finish
            "发布成功".toast()
            hideLoading()
            finish()
        }
    }

    private lateinit var countDownTimer: CountDownTimer
    var uploadLoadingDialog: AlertDialog? = null
    fun showLoading() {
        uploadLoadingDialog = PopUtils.uploadLoadingDialog(this, object : PopUtils.ICallback4Progress {
            override fun progressCallback(progress: MyCircleProgress, tvProgress: TextView) {
                countDownTimer = object : CountDownTimer(60000, 3000) {
                    override fun onTick(millisUntilFinished: Long) {
                        val pro = (60000 - millisUntilFinished) / 1000
                        progress.setMax(60)
                        progress.setCurrent(pro.toInt())
                    }

                    override fun onFinish() {}
                }.start()
            }
        })
        if (!uploadLoadingDialog!!.isShowing) {
            uploadLoadingDialog!!.show()
        }
    }

    fun hideLoading() {
        countDownTimer.cancel()
        if (uploadLoadingDialog.checkNotNull()) {
            uploadLoadingDialog!!.dismiss()
        }
    }

    override fun onDestroy() {
        if (EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this)
        }
        super.onDestroy()
    }
}